#!/usr/bin/env python

from optparse import OptionParser
from os import close, makedirs, pardir, remove
from os.path import dirname, isdir, join
from tempfile import mkstemp
from subprocess import call

from util import (
    VERSION,
    getResourcesDirectory,
    getTemplatesDirectory,
    writeTemplate
)

def main():
    parser = OptionParser("usage: %prog [options]")
    parser.add_option("-d", "--doc-dir", action="store", default=None,
                      dest="docDir", help="Directory to build documentation in")
    options, args = parser.parse_args()
    if len(args):
        parser.error("incorrect number of required arguments")
    fd, doxyfilePath = mkstemp(prefix="Doxyfile")
    try:
        close(fd)
        docDir = options.docDir
        if docDir is None:
            docDir = join(getResourcesDirectory(), "documentation", "api")
        if not isdir(docDir):
            makedirs(docDir)
        data = {
            "docDir": docDir,
            "version": VERSION
        }
        writeTemplate(doxyfilePath, join(getTemplatesDirectory(), "Doxyfile"),
                      data)
        if call(["doxygen", doxyfilePath]):
            parser.error("documentation generation failed")
    finally:
        remove(doxyfilePath)

if __name__ == "__main__":
    main()
